export let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
const Base64Util = {

    /* will return a  Uint8Array type */
    decodeArrayBuffer(input) {
        var bytes = (input.length / 4) * 3;
        var ab = new ArrayBuffer(bytes);
        this.decode(input, ab);

        return ab;
    },
    removePaddingChars(input) {
        var lkey = _keyStr.indexOf(input.charAt(input.length - 1));
        if (lkey == 64) {
            return input.substring(0, input.length - 1);
        }
        return input;
    },
    decode(input) {
        //get last chars to see if are valid
        input = this.removePaddingChars(input);
        input = this.removePaddingChars(input);
        var byteStr = '[';
        var bytes = parseInt((input.length / 4) * 3, 10);

        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        var j = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        for (i = 0; i < bytes; i += 3) {
            //get the 3 octects in 4 ascii chars

            enc1 = _keyStr.indexOf(input.charAt(j++));
            enc2 = _keyStr.indexOf(input.charAt(j++));
            enc3 = _keyStr.indexOf(input.charAt(j++));
            enc4 = _keyStr.indexOf(input.charAt(j++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            if (parseInt(chr1) > 127) {
                chr1 = -(((~(chr1 & 0x7f)) & 0x7f) + 1);
            }

            if (parseInt(chr2) > 127) {
                chr2 = -(((~(chr2 & 0x7f)) & 0x7f) + 1);
            }
            if (parseInt(chr3) > 127) {
                chr3 = -(((~(chr3 & 0x7f)) & 0x7f) + 1);
            }

            byteStr += chr1 + ',';
            byteStr += chr2 + ',';
            byteStr += chr3 + ',';
        }
        if (byteStr.length > 0) {
            return byteStr.substring(0, byteStr.length - 1) + ']';
        }
        return byteStr + ']';
    }
}

export default Base64Util
